package com.langxin.site.util.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 请求相关的工具类
 * 
 */
public class ActionUtils {
	
    /**
     * Spring MVC获取request的三种方法：
     * <a href="http://yeelor.iteye.com/blog/1554795">http://yeelor.iteye.com/blog/1554795</a> 
     */
    public static HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
            .getRequest();
    }
    
    public static HttpServletResponse getResponse() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
            .getResponse();
    }
    
    /**获取请求IP*/
    public static String getIP() {
        HttpServletRequest request = ActionUtils.getRequest();
        String addr = request.getRemoteAddr();
        //haproxy代理后把真实访问ip放在http header的 “X-Forwarded-For”中
        String headerXForwardedFor = request.getHeader("X-Forwarded-For");
        return headerXForwardedFor == null ? addr : headerXForwardedFor;
    }

    /**获取服务器真实路径*/
    public static String getRealPath(String path) {
        HttpServletRequest request = ActionUtils.getRequest();
        return request.getSession().getServletContext().getRealPath(path);
    }
    
}
